import { ref } from 'vue'
import apis from '@/services/apis'
import type { UserInfoType } from '@/services/types'

import { acceptHMRUpdate, defineStore } from 'pinia'
import { merge } from 'lodash-es'

interface UserToken {
  userId: string
  curTeamId: string
  authorization: string
}

interface UserInfo {
  avatar: string
  username: string
  account: string
  wallet: {
    balance: number
    amount: number
    freeze: number
  }
  curTeam: {
    teamName: string
  }
}

export const useUserStore = defineStore('user', () => {
  const userInfo = ref<Partial<UserInfoType>>({})
  const isSign = ref(false)

  let localUserInfo = {}
  try {
    localUserInfo = JSON.parse(localStorage.getItem('USER_INFO') || '{}')
  } catch (error) {
    localUserInfo = {}
  }

  // 从 local读取
  if (!Object.keys(userInfo.value).length && Object.keys(localUserInfo).length) {
    userInfo.value = localUserInfo
  }

  function getUserDetailAction() {
    apis
      .getUserDetail()
      .send()
      .then((data) => {
        userInfo.value = { ...userInfo.value, ...data }
      })
      .catch(() => {
        // 删除缓存
        localStorage.removeItem('TOKEN')
        localStorage.removeItem('USER_INFO')
      })
  }

  // const token = ref(ls.get('token'))
  const token = ref<UserToken | undefined>()
  const info = ref<UserInfo | undefined>()
  const router = useRouter()

  function init() {
    setToken(ls.get('token'))
  }

  function setToken(value: UserToken) {
    api.defaults.logoutHandler = async (e: any) => {
      console.log('e=>', e)
      // 登录失效处理
      return logout()
    }
    if (!value) {
      // clear()
      return
    }
    token.value = value
    ls.set('token', value)
    // 设置token
    api.defaults.headers = {
      'x-access-user-id': value.userId,
      'x-access-team-id': value.curTeamId,
      'authorization': value.authorization,
    }
  }

  // 设置用户信息
  function set(value: UserInfo) {
    info.value = value
    ls.set('userInfo', value)
  }

  // 更新用户信息
  async function update(data: UserInfo & { [key: string]: any }) {
    set(merge(info.value, data))
    // return service.user.info.updatePerson(data)
    return info.value
  }

  // 清除用户
  function clear() {
    ls.remove('token')
    ls.remove('userInfo')
    token.value = undefined
    info.value = undefined
    // 登出时切断socket
    // useSocket().disconnect()
  }

  // 退出
  function logout() {
    clear()
    router.push('/login')
  }

  // 获取用户信息
  async function get() {
    try {
      const res = (await service.auth.info()) as UserInfo
      if (res) {
        set(res)
      }
      // 已登录用户时连接socket
      // useSocket().connect()
      // 获取ossToken
      oss.init()
    } catch (e) {
      logout()
    }
  }

  // 修改密码
  async function changePassword(data: {
    oldPassword: string
    newPassword: string
    confirmPassword: string
  }) {
    return await service.auth.changePassword(data)
  }

  return {
    userInfo,
    isSign,
    getUserDetailAction,
    init,
    token,
    info,
    get,
    setToken,
    set,
    update,
    logout,
    changePassword,
  }
})

if (import.meta.hot) {
  // import.meta.hot.accept(acceptHMRUpdate(useUserStore as any, import.meta.hot))
  import.meta.hot.accept(() => {
    acceptHMRUpdate(useUserStore as any, import.meta.hot)
    console.log('热更新触发，用户信息已还原')
    useUserStore().init()
  })
}
